from PyQt6.QtWidgets import QWidget, QLabel, QVBoxLayout
from PyQt6.QtCore import Qt, QPropertyAnimation, QEasingCurve, QTimer, QRect, QRectF, pyqtProperty, QPointF
from PyQt6.QtGui import (QPainter, QColor, QPainterPath, QFont, QLinearGradient, 
                        QPen, QConicalGradient, QBrush, QRadialGradient, QFontDatabase)
import win32com.client
import pythoncom
import os
import sys

class BaseCountdownWidget(QWidget):
    def __init__(self, parent=None, enable_voice=True):
        super().__init__(parent)
        self.enable_voice = enable_voice
        if self.enable_voice:
            self.init_voice_engine()
            
    def init_voice_engine(self):
        pythoncom.CoInitialize()
        try:
            self.speaker = win32com.client.Dispatch("SAPI.SpVoice")
            self.speaker.Rate = 0
            self.speaker.Volume = 100
        except:
            self.speaker = None
            print("语音引擎初始化失败")
            
    def speak_text(self, text):
        if self.enable_voice and hasattr(self, 'speaker') and self.speaker:
            try:
                self.speaker.Speak(text, 1)
            except:
                print("语音播放失败")
                
    def closeEvent(self, event):
        if self.enable_voice and hasattr(self, 'speaker'):
            pythoncom.CoUninitialize()
        super().closeEvent(event)

class CircularCountdown(BaseCountdownWidget):
    def __init__(self, parent=None, enable_voice=True):
        super().__init__(parent, enable_voice)
        self._progress = 0
        self._hue = 0
        self._time_text = ""
        self._hint_text = "时间即将结束"
        
        self.color_timer = QTimer(self)
        self.color_timer.timeout.connect(self._update_hue)
        self.color_timer.start(50)
        
        self.initUI()
        
    def _update_hue(self):
        self._hue = (self._hue + 2) % 360
        self.update()
        
    def _get_progress(self):
        return self._progress
        
    def _set_progress(self, value):
        self._progress = max(0, min(1, value))
        self.update()
        
    progress = pyqtProperty(float, _get_progress, _set_progress)
    
    def initUI(self):
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
    def setText(self, text):
        self._time_text = text
        self.update()
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 设置时间标签字体
        time_font = QFont('Segoe UI', 72, QFont.Weight.Bold)
        painter.setFont(time_font)
        
        # 计算文本位置
        time_metrics = painter.fontMetrics()
        time_width = time_metrics.horizontalAdvance(self._time_text)
        time_x = (self.width() - time_width) / 2
        time_y = self.height() / 2 - 20
        
        # 绘制时间标签阴影
        shadow_color = QColor(100, 0, 0, 100)
        painter.setPen(shadow_color)
        painter.drawText(QPointF(time_x + 2, time_y + 2), self._time_text)
        
        # 绘制时间标签发光效果
        for i in range(3):
            alpha = int(150 * (3 - i) / 3)
            glow_color = QColor(255, 50, 0, alpha)
            painter.setPen(glow_color)
            offset = i * 0.5
            painter.drawText(QPointF(time_x - offset, time_y), self._time_text)
            painter.drawText(QPointF(time_x + offset, time_y), self._time_text)
            painter.drawText(QPointF(time_x, time_y - offset), self._time_text)
            painter.drawText(QPointF(time_x, time_y + offset), self._time_text)
        
        # 绘制时间标签主文本
        painter.setPen(QColor(255, 34, 0))
        painter.drawText(QPointF(time_x, time_y), self._time_text)
        
        # 设置提示标签字体
        hint_font = QFont('Microsoft YaHei UI Light', 24)
        painter.setFont(hint_font)
        
        # 计算提示文本位置
        hint_metrics = painter.fontMetrics()
        hint_width = hint_metrics.horizontalAdvance(self._hint_text)
        hint_x = (self.width() - hint_width) / 2
        hint_y = self.height() / 2 + 40
        
        # 绘制提示标签阴影
        painter.setPen(QColor(100, 0, 0, 80))
        painter.drawText(QPointF(hint_x + 1, hint_y + 1), self._hint_text)
        
        # 绘制提示标签发光效果
        for i in range(2):
            alpha = int(100 * (2 - i) / 2)
            glow_color = QColor(255, 50, 0, alpha)
            painter.setPen(glow_color)
            offset = i * 0.3
            painter.drawText(QPointF(hint_x - offset, hint_y), self._hint_text)
            painter.drawText(QPointF(hint_x + offset, hint_y), self._hint_text)
            painter.drawText(QPointF(hint_x, hint_y - offset), self._hint_text)
            painter.drawText(QPointF(hint_x, hint_y + offset), self._hint_text)
        
        # 绘制提示标签主文本
        painter.setPen(QColor(255, 34, 0))
        painter.drawText(QPointF(hint_x, hint_y), self._hint_text)
        
        # 圆环
        pen_width = 24
        margin = pen_width / 2
        rect = QRectF(margin, margin, self.width() - 2 * margin, self.height() - 2 * margin)
        
        # 绘制文字背景圆形
        center_radius = min(rect.width(), rect.height()) * 0.35  # 圆形背景的半径
        center_rect = QRectF(
            rect.center().x() - center_radius,
            rect.center().y() - center_radius,
            center_radius * 2,
            center_radius * 2
        )
        # 创建径向渐变
        gradient = QRadialGradient(rect.center(), center_radius)
        gradient.setColorAt(0, QColor(0, 0, 0, 180))  # 中心较深
        gradient.setColorAt(1, QColor(0, 0, 0, 100))  # 边缘较浅
        painter.setBrush(gradient)
        painter.setPen(Qt.PenStyle.NoPen)  # 不绘制边框
        painter.drawEllipse(center_rect)
        
        pen = QPen()
        pen.setWidth(pen_width)
        pen.setCapStyle(Qt.PenCapStyle.RoundCap)
        
        # 背景圆环
        pen.setColor(QColor(255, 255, 255, 30))
        painter.setPen(pen)
        painter.drawArc(rect.toRect(), 0, 360 * 16)
        
        # 进度圆环
        if self._progress > 0:
            gradient = QConicalGradient(rect.center(), -90)
            base_hue = self._hue
            for i in range(0, 360, 40):
                hue = (base_hue + i) % 360
                color = QColor.fromHsv(hue, 200, 250, 255)
                gradient.setColorAt(i / 360.0, color)
            gradient.setColorAt(1.0, QColor.fromHsv(base_hue, 200, 250, 255))
            
            pen.setBrush(gradient)
            painter.setPen(pen)
            
            start_angle = 90 * 16
            span_angle = int(-self._progress * 360 * 16)
            painter.drawArc(rect.toRect(), start_angle, span_angle)

class BubbleCountdown(BaseCountdownWidget):
    def __init__(self, parent=None, enable_voice=True):
        super().__init__(parent, enable_voice)
        self._progress = 0
        self.initUI()
        
    def _get_progress(self):
        return self._progress
        
    def _set_progress(self, value):
        self._progress = max(0, min(1, value))
        self.update()
        
    progress = pyqtProperty(float, _get_progress, _set_progress)
    
    def initUI(self):
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 增加气泡大小
        self.setFixedSize(300, 160)
        
        # 调整标签位置和大小
        self.time_label = QLabel(self)
        self.time_label.setGeometry(30, 20, 240, 80)
        self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 添加提示文本标签
        self.hint_label = QLabel("剩余时间", self)
        self.hint_label.setGeometry(30, 90, 240, 40)
        self.hint_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 设置样式
        self.time_label.setStyleSheet("""
            QLabel {
                color: white;
                font-size: 54px;
                font-weight: bold;
                font-family: 'Segoe UI', 'Microsoft YaHei UI';
                padding-bottom: 10px;
            }
        """)
        
        self.hint_label.setStyleSheet("""
            QLabel {
                color: rgba(255, 255, 255, 180);
                font-size: 16px;
                font-family: 'Microsoft YaHei UI Light';
                letter-spacing: 2px;
            }
        """)
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 绘制气泡
        path = QPainterPath()
        rect = QRectF(self.rect()).adjusted(15, 15, -15, -25)
        path.addRoundedRect(rect, 20, 20)  # 增加圆角半径
        
        # 计算小三角的点
        triangle_base = rect.bottomRight()
        points = [
            QPointF(triangle_base.x() - 40, triangle_base.y()),
            QPointF(triangle_base.x() - 20, triangle_base.y() + 20),
            QPointF(triangle_base.x(), triangle_base.y())
        ]
        
        # 添加小三角
        path.moveTo(points[0])
        for point in points:
            path.lineTo(point)
        
        # 创建渐变背景
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        alpha = int(230 * self._progress)
        
        # 使用更丰富的渐变色
        gradient.setColorAt(0, QColor(41, 128, 185, alpha))  # 蓝色
        gradient.setColorAt(0.5, QColor(52, 152, 219, alpha))  # 浅蓝色
        gradient.setColorAt(1, QColor(41, 128, 185, alpha))  # 蓝色
        
        # 绘制主体气泡
        painter.fillPath(path, QBrush(gradient))
        
        # 添加内发光效果
        glow = QRadialGradient(rect.center(), min(rect.width(), rect.height()) / 2)
        glow.setColorAt(0, QColor(255, 255, 255, int(40 * self._progress)))
        glow.setColorAt(1, QColor(255, 255, 255, 0))
        painter.fillPath(path, QBrush(glow))
        
        # 添加边缘高光
        highlight_pen = QPen(QColor(255, 255, 255, int(50 * self._progress)))
        highlight_pen.setWidth(2)
        painter.setPen(highlight_pen)
        painter.drawPath(path)

class ClockCountdown(BaseCountdownWidget):
    def __init__(self, parent=None, enable_voice=True):
        super().__init__(parent, enable_voice)
        self._progress = 0
        self.load_custom_font()
        self.initUI()
        self._text = "00:00:00"  # 添加文本存储
        
    def load_custom_font(self):
        # 加载自定义字体
        try:
            # 检查是否是打包后的环境
            if getattr(sys, 'frozen', False):
                # 如果是打包后的环境，使用 _MEIPASS
                base_path = sys._MEIPASS
            else:
                # 如果是开发环境，使用相对路径
                base_path = os.path.dirname(os.path.dirname(__file__))
                
            font_path = os.path.join(base_path, 'resources', 'digital-7-mono-3.ttf')
            font_id = QFontDatabase.addApplicationFont(font_path)
            if font_id != -1:
                self.font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
                print(f"Successfully loaded font: {self.font_family}")
            else:
                print(f"Error: Could not load font file from {font_path}")
                self.font_family = 'monospace'
        except Exception as e:
            print(f"Font loading error: {str(e)}")
            self.font_family = 'monospace'
        
    def _get_progress(self):
        return self._progress
        
    def _set_progress(self, value):
        self._progress = max(0, min(1, value))
        self.update()
        
    progress = pyqtProperty(float, _get_progress, _set_progress)
    
    def initUI(self):
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(1050, 200)  # 增加宽度到1000
        
    def setText(self, text):
        self._text = text
        self.update()
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 设置字体
        font = QFont(self.font_family, 160)
        font.setBold(True)
        font.setLetterSpacing(QFont.SpacingType.AbsoluteSpacing, 8)
        painter.setFont(font)
        
        # 计算文本位置
        metrics = painter.fontMetrics()
        text_width = metrics.horizontalAdvance(self._text)
        text_x = (self.width() - text_width) / 2
        text_y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        
        # 创建文本绘制点
        text_point = QPointF(text_x, text_y)
        
        # 绘制深色阴影
        shadow_offset = 4
        shadow_color = QColor(0, 20, 0)
        painter.setPen(shadow_color)
        painter.drawText(QPointF(text_x + shadow_offset, text_y + shadow_offset), self._text)
        
        # 绘制暗色背景数字
        painter.setPen(QColor(0, 15, 0))  # 更暗的背景色
        painter.drawText(text_point, self._text)
        
        # 绘制主要发光效果
        main_color = QColor(0, 100, 0)  # 暗绿色
        
        # 绘制内发光
        for i in range(4):
            inner_glow = QColor(0, 100, 0, int(40 * self._progress))
            blur_pen = QPen(inner_glow)
            blur_pen.setWidth(i)
            painter.setPen(blur_pen)
            painter.drawText(text_point, self._text)
        
        # 绘制主文本
        painter.setPen(QColor(0, 130, 0))  # 暗绿色主色
        painter.drawText(text_point, self._text)
        
        # 添加LED发光效果
        glow_steps = 5
        for i in range(glow_steps):
            alpha = int(50 * self._progress * (glow_steps - i) / glow_steps)
            glow_color = QColor(0, 150, 0, alpha)
            painter.setPen(QPen(glow_color, 1))
            offset = i * 0.5
            painter.drawText(QPointF(text_x - offset, text_y), self._text)
            painter.drawText(QPointF(text_x + offset, text_y), self._text)
            painter.drawText(QPointF(text_x, text_y - offset), self._text)
            painter.drawText(QPointF(text_x, text_y + offset), self._text)
        
        # 添加高光效果
        if self._progress > 0.5:
            highlight_color = QColor(0, 180, 0, int(20 * self._progress))
            painter.setPen(highlight_color)
            painter.drawText(QPointF(text_x, text_y - 1), self._text)
            
        # 最外层发光晕
        outer_glow_steps = 3
        for i in range(outer_glow_steps):
            alpha = int(15 * self._progress * (outer_glow_steps - i) / outer_glow_steps)
            outer_glow = QColor(0, 160, 0, alpha)
            painter.setPen(QPen(outer_glow, 1))
            offset = i + 2
            painter.drawText(QPointF(text_x - offset, text_y), self._text)
            painter.drawText(QPointF(text_x + offset, text_y), self._text)
            painter.drawText(QPointF(text_x, text_y - offset), self._text)
            painter.drawText(QPointF(text_x, text_y + offset), self._text)
        
    def mousePressEvent(self, event):
        self.close() 